package com.ssyx.service.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.ssyx.exception.SsyxException;
import com.ssyx.result.ResultCodeEnum;
import com.ssyx.service.FileUploadService;
import lombok.extern.slf4j.Slf4j;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.Objects;
import java.util.UUID;

/**
 * @program: ssyx-parent
 * @className: FileUploadServiceImpl
 * @description: 文件上传类
 * @data: 2024/3/12 20:06
 * @author: ihu
 * @version: 1.0
 **/

@Slf4j
@Service
public class FileUploadServiceImpl implements FileUploadService {
	
	@Value("${ssyx.alioss.endpoint}")
	private String endPoint;
	@Value("${ssyx.alioss.access-key-id}")
	private String accessKey;
	@Value("${ssyx.alioss.access-key-secret}")
	private String secreKey;
	@Value("${ssyx.alioss.bucket-name}")
	private String bucketName;
	
	@Override
	public String fileUpload(MultipartFile file) {
		try {
			// 创建OSSClient实例。
			OSS ossClient = new OSSClientBuilder().build(endPoint, accessKey, secreKey);
			// 上传文件流
			InputStream inputStream = file.getInputStream();
			//文件后缀名
			String name =
					Objects.requireNonNull(file.getOriginalFilename()).substring(file.getOriginalFilename().lastIndexOf("."));
			log.info("上传文件后缀名：{}", name.replace(".", ""));
			//生成随机唯一值，使用uuid，按照当前日期，创建文件夹，上传到创建文件夹里面
			// 2021/02/02/01.jpg
			String fileName = "ssyx/" + new DateTime().toString("yyyy/MM/dd") + "/" + UUID.randomUUID() + name;
			// 调用方法实现上传
			ossClient.putObject(bucketName, fileName, inputStream);
			// 关闭OSSClient
			ossClient.shutdown();
			// 上传之后文件路径
			String path = "https://" + bucketName + "." + endPoint + "/" + fileName;
			log.info("文件上传成功，文件路径是：{}", path);
			return path;
		} catch (IOException e) {
			log.error("文件上传失败", e);
			throw new SsyxException(ResultCodeEnum.URL_ENCODE_ERROR);
		}
	}
}
